package com.aneliya.validator.suite;

import java.util.EventObject;

import javax.swing.JLabel;
import javax.swing.event.EventListenerList;

import com.aneliya.validator.Validator;
import com.aneliya.validator.ValidatorListener;

public class ValidationItem extends Validator {
	protected Validator componentValidator;
	protected JLabel errorLabel;
	protected String errorMessage;
	protected Boolean valid = false;
	
	public Boolean isValid() {
		return valid;
	}
	
	public ValidationItem(
			Validator componentValidator,
			JLabel errorLabel,
			String errorMessage) {
		super();
		
		this.componentValidator = componentValidator;
		this.errorLabel = errorLabel;
		this.errorMessage = errorMessage;
		
		listeners = new EventListenerList();
		
		createValidatorListener();
	}

	protected void createValidatorListener() {
		ValidatorListener listener = new ValidatorListener() {
			public void validatorChanged(EventObject e) {
				checkValidator();
			}
		};
		componentValidator.addValidatorListener(listener);
	}
	
	protected void checkValidator() {
		if (componentValidator.isActive()) {
			Boolean newValid = componentValidator.isValid();
			if (newValid) {
				hideErrorMessage();
			} else {
				showErrorMessage();
			}

			if (newValid != valid) {
				valid = newValid;
				dispatchValidatorChanged();
			}
		}
	}
	
	private void showErrorMessage() {
		errorLabel.setText(errorMessage);
	}

	private void hideErrorMessage() {
		errorLabel.setText(" ");
	}
	
}
